#! /usr/bin/env python
#coding=utf-8

"""

    2011 Boris Tatarintsev

    Class which manages local highscores i.e.
    save score table on disk, load score table from disk, etc.

"""

import urllib
import socket
import tools
import binascii

import __main__

from hsbasic     import HSBasic


class HSRemote(HSBasic):

    #SITE_URL = "http://mysite.ru/index.html"
    SITE_URL = "http://pydotter.atwebpages.com/index.html"

    # init network status window

    def __init__(self):
        HSBasic.__init__(self)
        self.createEmptyScoreTables()


    def getHostIP(self, hostname):
        return socket.gethostbyname(hostname)

    def getServerResponse(self, request):
        try:
            f = urllib.urlopen(HSRemote.SITE_URL, request)
            response = f.read()
            return response
        except IOError:
            raise

    def getRemoteScores(self, gameMode):
        """Requests remote score data from server """
        try:
            p = urllib.urlencode({'action': 'get_scores', 'mode': gameMode})
            response = self.getServerResponse(p).rstrip(';')[:-2]
            response = list(map(lambda x: x.split(','), response.split(';')))
            if response[0] != ['']:
                for item in response:
                    item[1] = int(item[1])
                    item.append(None)
            # create scores structure
            self.buildScoreTableFromList(response, __main__.Game.getGameTypeString(gameMode))
            return response
        except IOError:
            raise

    def getUserReplayData(self, username):
        """Get replay data """
        pass

    def sendScore(self, username, score, gameMode, replayData = None):
        """Sends new highscore to server """
        try:
            self.getRemoteScores(gameMode)
            src = tools.serialize(replayData).getvalue()
            encrypted = tools.xorEncrypt(src).getvalue()
            p = urllib.urlencode({'action': 'set_score', 'username': username, 'score': score, 'mode': gameMode, \
                                  'replay': encrypted, 'crc': binascii.crc32(src)})
            response = self.getServerResponse(p)
        except IOError:
            raise

    def insertScore(self, tableName, playerName, score, userData = None):
        try:
            gameType = __main__.Game.getGameTypeID(tableName)
            self.getRemoteScores(gameType)
            if self.isHighScore(tableName, score):
                self.sendScore(playerName, score, gameType, userData)
                self.getRemoteScores(gameType)
        except IOError:
            raise

    def loadScores(self, gameMode = 0):
        try:
            self.getRemoteScores(__main__.Game.getGameTypeID(gameMode))
        except IOError:
            raise
